import React, {
	PureComponent
} from 'react'
import { connect } from 'dva'
import moment from 'moment'
import { Row, Col, Form, Switch, Input, Button, DatePicker } from 'antd'
import Icon from 'react-fa'
import Grid from '@/components/Grid'
import Select from '@/components/Select'
import Dialog, { withRef } from '@/components/Dialog'
import settings, { getPagination } from '@/settings'
import { /*numberFormat, */mapping, download, isAdmin } from '@/utils'
import { $request } from '@/utils/request'
import Authorized, { checkRouteAuth } from '@/components/Authorized'

const swap = (array, x, y) => {
    array[x] = array.splice(y, 1, array[x])[0];
    return array;
}

@Form.create()
@connect(({ app: { user={} }, issue: { data={}, units=[] } }) => ({ user, data, units }))
@withRef
class ModelForm extends React.Component {
	componentDidMount() {
		const {
			id,
			user,
			dispatch
		} = this.props;
		
		isAdmin(user) && dispatch({
			type: 'issue/fetchUnits'
		});
		if (id) {
			dispatch({
				type: 'issue/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	handleSubmit = (_, callback) => {
		const {
			data: {
				subjects = []
			},
			form
		} = this.props

		form.validateFields(['date', 'orgId'], (err, data) => {
			if (!err) {
				if (subjects.length === 0) {
					Dialog.alert('请输入议题，一条条添加后再提交')
					return
				}
				const {
					date
				} = data
				callback({
					...data,
					date: `${date[0].format('YYYY-MM-DD')}${settings.range}${date[1].format('YYYY-MM-DD')}`,
					subjects
				})
			}
		})
	};
	renderFields = () => {
		const {
			data: {
				subjects = []
			},
			form: {
				getFieldDecorator
			}
		} = this.props
		return (
			<div className="field-options">
				{ subjects.map((_, index) => {
					return (
						<div className="field-option" key={index}>
		                    <div className="field-option-body">
		                    	{!_.editable && <div className="field-option-data" onClick={e => this.handleMenuEvent(e, 'edit', index)}><span className="text-success"><Icon name="check-square-o" /></span> {_.title}</div>}
								{_.editable && <div className="field-option-form">
									<Form.Item style={{paddingBottom: 0}}>
										{getFieldDecorator(`subjects[${index}].title`, {
										  	initialValue: _.title,
										})(<Input.TextArea rows={2} ref={node => {this.editArea = node}} placeholder="请在此输入议题，请按一条条议题添加" onBlur={e => this.handleMenuEvent(e, 'save', index)} />)}
									</Form.Item>
								</div>}
							</div>
		                    <div className="field-option-footer">
		                        <span className="ico-btn" onClick={e => this.handleMenuEvent(e, 'edit', index)}><Icon name="edit" /></span>
		                        <span className="ico-btn text-danger" onClick={e => this.handleMenuEvent(e, 'remove', index)}><Icon name="minus-square" /></span>
		                        <span className="ico-btns">
		                            {index !== 0 && <span className="ico-btn" onClick={e => this.handleMenuEvent(e, 'movePrev', index)}><Icon name="caret-up" /></span>}
		                            {index !== subjects.length - 1 && <span className="ico-btn" onClick={e => this.handleMenuEvent(e, 'moveNext', index)}><Icon name="caret-down" /></span>}
		                        </span>
		                    </div>
		                </div>
					)
				}) }
            </div>
		)
	};
	handleMenuEvent(e, key, index) {
		e.stopPropagation()

		const {
			data,
			form,
			dispatch
		} = this.props

		const {
			subjects = []
		} = data

		const values = subjects[index]

		switch (key) {
			case 'save' : 
				const title = form.getFieldValue(`subjects[${index}].title`)
				subjects[index] = {
					...values,
					title,
					editable: false
				}
				break
			case 'edit' : 
				subjects[index] = {
					...values,
					editable: true
				}
				setTimeout(() => {
					this.editArea && this.editArea.focus()
				}, 0)
				break
			case 'remove' : 
				subjects.splice(index, 1)
				break
			case 'movePrev' : 
				if (index > 0) {
					swap(subjects, index, index - 1);
				}
				break
			case 'moveNext' : 
				if (index < subjects.length - 1) {
	                swap(subjects, index, index + 1);
	            }
				break
			default :
		}

		dispatch({
			type: 'issue/updateState',
			payload: {
				data: {
					...data,
					subjects: [...subjects]
				}
			}
		})
	};
	handleAdd = e => {
		const {
			data,
			form,
			dispatch
		} = this.props

		const title = form.getFieldValue('title')

		form.setFieldsValue({
			'title': ''
		})
		
		const {
			subjects = []
		} = data

		dispatch({
			type: 'issue/updateState',
			payload: {
				data: {
					...data,
					subjects: [...subjects, {
						title
					}]
				}
			}
		})
	};
	render() {
		const {
			user,
			data,
			form: {
				getFieldDecorator
			},
			units = []
		} = this.props

		const options = units.map(_ => <Select.Option key={_.id} value={_.id}>{_.name}</Select.Option>)

		return (
			<Form layout="vertical">
				<Form.Item style={{paddingBottom: 12}}>
					<Form.Item style={{display: 'inline-block', paddingBottom: 0}}>
						{getFieldDecorator('date', {
						  rules: [{ required: true, message: '请选择开始时间' }],
						  initialValue: data.date ? data.date.split(settings.range).map(_ => moment(_.trim())) : null,
						})(
						  <DatePicker.RangePicker
						    style={{ width: 220 }}
						  />
						)}
					</Form.Item>
					{isAdmin(user) && <Form.Item style={{display: 'inline-block', marginLeft: 12, paddingBottom: 0}}>
						{getFieldDecorator('orgId', {
						  rules: [{ required: true, message: '请选择选择部门' }],
						  initialValue: data.orgId,
						})(
						  <Select placeholder="请选择部门" style={{ width: 110 }}>
						    {options}
						  </Select>
						)}
					</Form.Item>}
				</Form.Item>
				<div className="area-form">
					<div className="area-form-body">
						{getFieldDecorator('title')(<Input.TextArea ref={node => {this.area = node}} rows={2} placeholder="请在此输入议题，请按一条条议题添加" />)}
					</div>
					<div className="area-form-footer" onClick={e => this.area.focus()}><Button type="primary" shape="round" size="small" icon="plus-circle" onClick={this.handleAdd}>添加</Button></div>
				</div>
				<div className="form-title">
					<h2>已添加议题列表：</h2>
				</div>
				{this.renderFields()}
	        </Form>
		)
	}
}

@Form.create()
@connect(({ issue: { data={} } }) => ({ data }))
@withRef
class ModelCheck extends React.Component {
	componentDidMount() {
		const {
			id,
			dispatch
		} = this.props;
		
		if (id) {
			dispatch({
				type: 'issue/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	handleSubmit = (_, callback) => {
		const {
			data,
			form
		} = this.props

		const {
			subjects = []
		} = data

		const values = form.getFieldValue('subjects')
		callback({
			...data,
			subjects: subjects.map((v, i) => {
				const _ = values[i]
				return {
					...v,
					text: _.text,
					status: _.status ? 1: 0
				}
			})
		})
	};
	handleChange(checked, index) {
		const {
			data,
			dispatch
		} = this.props

		const {
			subjects = []
		} = data

		const v = subjects[index]

		subjects[index] = {
			...v,
			status: !!checked ? 1 : 0
		}

		dispatch({
			type: 'issue/updateState',
			payload: {
				data: {
					...data,
					subjects: [...subjects]
				}
			}
		})
	};
	render() {
		const {
			data,
			form: {
				getFieldDecorator
			}
		} = this.props

		const {
			subjects = []
		} = data

		return (
			<Form layout="vertical">
				<Row gutter={24}>
					<Col span={12}>日期：<span className="text-info">{data.date}</span></Col>
					<Col span={12} style={{textAlign: 'right'}}>部门：{data.orgName}</Col>
				</Row>
				<div className="field-options">
					{subjects.map((_, index) => (
	                    <div className="field-option" key={index}>
	                        <div className="field-option-body">
	                        	<div className="field-option-data"><span className="text-info"><Icon name="clock-o" /></span> {_.title}</div>
	                            {!_.status && <div className="field-option-form">
									<Form.Item style={{paddingBottom: 0}}>
										{getFieldDecorator(`subjects[${index}].text`, {
										  	initialValue: _.text,
										})(<Input.TextArea rows={4} placeholder="未完成原因" />)}
									</Form.Item>
								</div>}
							</div>
	                        <div className="field-option-footer">
	                            <label className="text-danger">是否完成：</label>
								{getFieldDecorator(`subjects[${index}].status`, {
									valuePropName: 'checked',
									initialValue: !!_.status,
								})(<Switch checkedChildren="是" unCheckedChildren="否" onChange={checked => this.handleChange(checked, index)} />)}
	                        </div>
	                    </div>
					))}
                </div>
	        </Form>
		)
	}
}

@connect(({ issue: { data={} } }) => ({ data }))
class ModelPreview extends React.Component {
	componentDidMount() {
		const {
			id,
			dispatch
		} = this.props;
		
		if (id) {
			dispatch({
				type: 'issue/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	render() {
		const {
			data
		} = this.props

		const {
			subjects = []
		} = data

		return (
			<React.Fragment>
				<Row gutter={24}>
					<Col span={12}>日期：<span className="text-info">{data.date}</span></Col>
					<Col span={12} style={{textAlign: 'right'}}>部门：{data.orgName}</Col>
				</Row>
				<div className="field-options">
					{subjects.map((_, index) => (
		                <div className="field-option" key={index}>
		                    <div className="field-option-body">
		                    	<div className="field-option-data"><span className="text-info"><Icon name="clock-o" /></span> {_.title}</div>
		                        {!_.status && _.text && <div className="field-option-form">
									<span className="text-danger">原因：<strong>{_.text}</strong></span>
								</div>}
							</div>
		                    <div className="field-option-footer">
		                        {!!_.status ? <label className="text-success">已完成</label> : <label className="text-danger">未完成</label>}
		                    </div>
		                </div>
	                ))}
	            </div>
	        </React.Fragment>
		)
	}
}

@connect(({
	app: {
		user = {}
	},
	issue: {
		list = {},
		params,
		years = []
	},
	loading
}) => ({
	user,
	list,
	params,
	years,
	loading: loading.effects['issue/fetchAll'],
}))
@Form.create()
class TaskIssuePage extends PureComponent {
	state = {
		selectedRows: []
	};
	columns = [{
		title: '月份',
		dataIndex: 'month',
		width: 100,
		render: (v, record, index) => {
			// return `${numberFormat(v)}月`
			const start = record.startDate
			return moment(start).format('MMMM')
		},
		align: 'center'
	}, {
		title: '时间',
		dataIndex: 'date',
		width: 300,
		render: (v, record, index) => {
			const start = record.startDate
			const end = record.endDate
			return `${moment(start).format('MM月DD日')} - ${moment(end).format('MM月DD日')}`
		},
		align: 'center'
	}, {
		title: '部门',
		dataIndex: 'orgId',
		width: 200,
		render: (v, record, index) => {
			const {
				list: {
					fields = {}
				}
			} = this.props
			const {
				orgs = {}
			} = fields
			const { items=[] } = record

			return (
				<div className="inner-table">
					<table cellSpacing="0" cellPadding="0">
						<tbody>
							{
								items.map((r, index) => {
									return (
										<tr key={index}><td>{mapping(r.orgId, orgs)}</td></tr>
									)
								})
							}
						</tbody>
					</table>
				</div>
			)
		},
		align: 'center'
	}, {
		title: '操作',
		dataIndex: 'id',
		width: 250,
		render: (v, record, index) => {
			const {
				user: {
					authorities = []
				}
			} = this.props
			const { items=[] } = record

			return (
				<div className="inner-table">
					<table cellSpacing="0" cellPadding="0">
						<tbody>
							{
								items.map((r, index) => {
									return (
										<tr key={index}>
											<td>
												{r.status===0 && checkRouteAuth(authorities)('ISSUE_REVIEW') && <span className="btn-text text-warning" onClick={e => this.handleMenuEvent(e, 'verify', r.id)}><Icon name="check-circle" />审核</span>}
												{r.status===0 && checkRouteAuth(authorities)('ISSUE_EDIT') && <span className="btn-text" onClick={e => this.handleMenuEvent(e, 'edit', r.id)}>修改</span>}
												{r.status===0 && checkRouteAuth(authorities)('ISSUE_DEL') && <span className="btn-text text-danger" onClick={e => this.handleMenuEvent(e, 'remove', r.id)}><Icon name="minus-circle" />删除</span>}
												{r.status===1 && checkRouteAuth(authorities)('ISSUE_ACTION') && <span className="btn-text text-warning" onClick={e => this.handleMenuEvent(e, 'check', r.id)}><Icon name="bolt" />督办</span>}
												<Authorized authorities={authorities} authority="ISSUE_PREVIEW"><span className="btn-text" onClick={e => this.handleMenuEvent(e, 'preview', r.id)}>查看</span></Authorized>
											</td>
										</tr>
									)
								})
							}
						</tbody>
					</table>
				</div>
			)
		},
		align: 'center'
	}];
	componentDidMount() {
		const {
			dispatch,
			years = []
		} = this.props;
		dispatch({
			type: 'issue/years'
		})
		dispatch({
			type: 'issue/fetchAll',
			year: years[0]
		});
	};
	handleMenuEvent(e, key, id) {
		e.stopPropagation()

		switch (key) {
			case 'verify':
				this.handleVerify(e, id)
				break
			case 'edit':
				this.handleEdit(e, id)
				break
			case 'check':
				this.handleCheck(e, id)
				break
			case 'preview':
				this.handlePreview(e, id)
				break
			default :
		}
	};
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};
	handleAdd = e => {
		const {
			user,
			dispatch
		} = this.props;
		dispatch({
			type: 'issue/reset'
		});
		Dialog.open({
			title: '新建议题',
			width: '70%',
			fixed: true,
			component: ModelForm,
			url: 'issue/task/add',
			onOk: data => {
				this.handleReload()
			},
			connect: isAdmin(user) ? ({ loading }) => ({ loading: loading.effects['issue/fetchUnits'] }) : null
		})
	};
	handleEdit = (e, id) => {
		if (id === undefined) {
			const { selectedRows } = this.state;
			id = selectedRows[0].id;
		}
		const {
			user,
			dispatch
		} = this.props;
		dispatch({
			type: 'issue/reset'
		});
		Dialog.open({
			title: '修改议题',
			width: '70%',
			fixed: true,
			url: 'issue/task/update',
			data: {
				id
			},
			options: {
				type: 'put'
			},
			onOk: data => {
				this.handleReload()
			},
			component: props => (<ModelForm {...props} id={id} />),
			connect: ({ loading }) => ({ loading: (isAdmin(user) ? loading.effects['issue/fetchUnits'] : true) && loading.effects['issue/fetchOne'] })
		})
	};
	handleRemove = e => {
		const { selectedRows } = this.state;
		Dialog.confirm({
			title: '确认提示',
			content: '确定要删除已选择的任务？',
			onOk: () => {
				$request.put('issue/task/delete', {
					data: {
						ids: selectedRows.map(_ => _.id)
					}
				}).then(data => {
					this.handleReload()
				})
			}
		})
	};
	handleVerify = (e, id) => {
		Dialog.confirm({
			title: '确认提示',
			content: '确定要通过选中的议题？',
			onOk: () => {
				$request.put('issue/task/pass', {
					data: {
						ids: [id]
					}
				}).then(data => {
					this.handleReload()
				})
			}
		})
	};
	handleCheck = (e, id) => {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'issue/reset'
		});
		Dialog.open({
			title: '督办工作完成情况',
			width: '70%',
			fixed: true,
			url: 'issue/task/save',
			data: {
				id
			},
			options: {
				type: 'put'
			},
			onOk: data => {
				this.handleReload()
			},
			component: props => (<ModelCheck {...props} id={id} />),
			connect: ({ loading }) => ({ loading: loading.effects['issue/fetchOne'] })
		})
	};
	handlePreview = (e, id) => {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'issue/reset'
		});
		Dialog.open({
			title: '计划详情',
			width: '70%',
			fixed: true,
			showCancel: false,
			okText: '关闭',
			component: props => (<ModelPreview {...props} id={id} />),
			connect: ({ loading }) => ({ loading: loading.effects['issue/fetchOne'] })
		})
	};
	handleExport = e => {
		const { selectedRows } = this.state;
		if (selectedRows.length > 0) {
			let ids = selectedRows.map(function(r) {
					return r.items.map(function(i) {
						return i.id
					})
				})
			const flat = arr => [].concat(...arr);
			ids = flat(ids)
			Dialog.confirm({
				title: '确认提示',
				content: '确定要导出已选择的议题？',
				onOk: () => {
					download('api/issue/task/exports', {
						ids: ids,
						onlyWeek: selectedRows.length === 1
					})
				}
			})
		} else {
			const {
				form
			} = this.props

			const year = form.getFieldValue('year')

			Dialog.confirm({
				title: '确认提示',
				content: `确定要导出${year}年的议题？`,
				onOk: () => {
					download('api/issue/task/exports', {
						year
					})
				}
			})
		}
	};
	handleGridChange = (oldPagination, sorter) => {
		const { params, dispatch, years } = this.props;
		
		const pagination = getPagination(oldPagination)
		const payload = {
			year: years[0],
			...params,
			...pagination
		}

		if (sorter.field) {
			payload.sorter = sorter.field
			payload.order = sorter.order
		}

		dispatch({
			type: 'issue/fetchAll',
			payload,
		})
	};
	handleReload = () => {
		const { params, dispatch, years } = this.props;
		dispatch({
			type: 'issue/fetchAll',
			payload: {
				year: years[0],
				...params
			}
		})
	};
	// handleSearch = (value, e) => {
	// 	e.preventDefault();
	// 	const { params, dispatch } = this.props;
	// 	const pagination = getPagination({
	// 		pageNumber: 1
	// 	})
	// 	dispatch({
	// 		type: 'issue/fetchAll',
	// 		payload: {
	// 			...params,
	// 			...pagination,
	// 			name: value
	// 		}
	// 	})
	// };
	handleSubmit = e => {
		e.preventDefault()

		const {
			form,
			years
		} = this.props

		form.validateFields((err, values) => {
			const { params, dispatch } = this.props;
			const pagination = getPagination({
				pageNumber: 1
			})
			dispatch({
				type: 'issue/fetchAll',
				payload: {
					year: years[0],
					...params,
					...pagination,
					...values
				}
			})
		})
	};
	render() {
		const { selectedRows } = this.state;
		const {
			user: {
				authorities = []
			},
			params,
			form: {
				getFieldDecorator
			},
			loading,
			list: {
				data,
				total
			},
			years
		} = this.props

		const pageNumber = params[settings.pageNumber]

		const options = years.map(_ => <Select.Option key={_} value={_}>{_}</Select.Option>)
		return (
			<div className="x-wrap">
				<div className="x-panel">
					<div className="x-toolbar">
						<div className="fl">
							<Authorized authorities={authorities} authority="ISSUE_ADD"><Button type="primary" onClick={this.handleAdd}>新建</Button></Authorized>
							<Authorized authorities={authorities} authority="ISSUE_EXPORT"><Button icon="cloud-download" onClick={this.handleExport}>导出议题</Button></Authorized>
						</div>
						<div className="fr x-query">
							<Form layout="inline" onSubmit={this.handleSubmit}>
								<Form.Item>
						            {getFieldDecorator('year', {
						            	initialValue: years[0]
						            })(
						              <Select placeholder="请选择" style={{width: 100}}>
						                	{options}
						              </Select>
						            )}
						        </Form.Item>
					          	<Form.Item>
						            <Button type="primary" htmlType="submit">查询</Button>
						        </Form.Item>
							</Form>
						</div>
					</div>
					<div className="x-fixed">
						<Grid 
						className="x-grid-apply"
						selectedRows={selectedRows} 
						onSelectRow={this.handleSelectRows} 
						columns={this.columns} 
						data={data}
						loading={loading}
						pagination={{
							pageNumber,
							total
						}}
						onReload={this.handleReload}
						onChange={this.handleGridChange} />
					</div>
				</div>
			</div>
		)
	}
}

export default TaskIssuePage